package com.byzk.p2p.app.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.bank.vo.BankCardVo;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.Constant;
import com.byzk.p2p.admin.base.util.CopyEntity;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.MD5;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.util.SHA;
import com.byzk.p2p.admin.borrow.dto.Borrow;
import com.byzk.p2p.admin.borrow.dto.BorrowApply;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.UserTenderVo;
import com.byzk.p2p.admin.fuiou.controller.FuionAccountController;
import com.byzk.p2p.admin.money.dto.RechargeRecord;
import com.byzk.p2p.admin.money.dto.WithdrawRecord;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.service.WithdrawService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.util.FundRecordTypeVo;
import com.byzk.p2p.admin.money.vo.FundRecordUserVo;
import com.byzk.p2p.admin.money.vo.RechargeRecordVo;
import com.byzk.p2p.admin.money.vo.WithdrawRecordVo;
import com.byzk.p2p.admin.system.service.SMSService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.admin.user.vo.UserAccountVo;

/**
 * 用户金额操作层
 * 
 * @author suker.zhou
 *
 */
@Controller
@RequestMapping("/app")
@Scope("prototype")
public class AppMoneyController extends BaseController {
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private TenderService tenderService;
	@Autowired
	private BorrowService borrowService;
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private UserService userService;
	@Autowired
	private FundRecordService fundRecordService; 
	@Autowired
	private SMSService sMSService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private UserAuthService userAuthService;
	@Autowired
	private FuionAccountController fuionAccountController;

	/**
	 * 查询用户资金信息接口
	 * 
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/account/info")
	public void userAccountInfo(@RequestParam Integer uid) throws Exception {
		try {
			if (uid==null) {
				super.printJSON(new JsonMsg(1, "请先登录！"));
				return;
			}
			UserAccountVo account=userAccountService.getAccountVoByUserId(uid);
			/*Double awaitFund = userAccountService.sumAwaitFundByUserId(uid);
			Double awaitInterest = userAccountService.sumAwaitInterestByUserId(uid);*/
			//赚取收益
			Double sumTenderInterest=tenderService.sumTenderInterest(uid);
			Map<String,Integer> auth = userAuthService.getUserAuthDetail(uid);
			Map<String,Object> result = new HashMap<String, Object>();
			if(account == null || auth == null){
				super.printJSON(new JsonMsg(0, "服务器异常，请稍后再试！"));
			}else{
				/*account.setAwaitFund(awaitFund);
				account.setAwaitInterest(awaitInterest);*/
				result.put("account", account);
				result.put("sumTenderInterest", sumTenderInterest);
				result.put("auth", auth);
				super.printJSON(new JsonMsg(-1, "查询成功！", result));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return;
	}

	@RequestMapping("/withdraw/sms")
	public String withdrawSms(@RequestParam("uid") Integer uid) throws Exception{
		Map<String, String> jsonMap = new HashMap<String, String>();
		User user=userService.getById(uid);
		if(user==null){
			super.printJSON(new JsonMsg(1, "请先登录"));
			return null;
		}
		int intCount = 0;
		intCount = new Random().nextInt(9999);
		if (intCount < 1000) {
			intCount += 1000;
		}
		String randomCode = "" + intCount;
		sMSService.sendwithdrawApplySms(user.getPhone(),randomCode,request.getRemoteAddr());
		jsonMap.put("randomCode", SHA.encryptPassword(randomCode+user.getPhone()));
		super.printJSON(new JsonMsg(-1, "发送成功",jsonMap));
		return null;
	}
	
	/**
	 * 用户提现接口
	 * 
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/withdraw/check")
	public String withdraw( @ModelAttribute WithdrawRecord info) throws Exception {
		Integer id = Constant.strToInt(info.getUid());
		User user=new User();
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return null;
		}else{
			user=userService.getById(id);
			if(user==null){
				super.printJSON(new JsonMsg(2, "非法登录"));
				return null;
			}else{
				if("N".equals(user.getFuionAccount())){
					super.printJSON(new JsonMsg(3, "该用户未开通托管功能"));
					return null;
				}
			}
			
			List<BankCard> cardList = bankCardService.listCardByUserId(user.getId());
			
			if(cardList.size()<1){
				super.printJSON(new JsonMsg(4, "请先绑定提现银行卡"));
				return null;				
			}
		}
		
		//查询金账户用户可用余额
		UserAccount accountFY = fuionAccountController.getFuionAccountBalance(user);
		if(accountFY.getBalance() < info.getMoney() ){
			printJSON(new JsonMsg(4, "您的金账户可用余额为￥"+accountFY.getBalance()+"元,提现金额超过此金额,无法提现."));
			return null;
		}
		
		UserAccount account=accountService.getByUserId(Integer.parseInt(info.getUid()));
		if(account.getBalance()<info.getMoney()){
			super.printJSON(new JsonMsg(4, "您的迅泊达可用余额为￥"+account.getBalance()+"元,提现金额超过此金额，无法提现."));
			return null;
		}
		if(info.getMoney()<=0){
			super.printJSON(new JsonMsg(3, "提现金额有误，请重新输入"));
			return null;			
		}
		//生成code并传至前台
		String mchnt_txn_ssn=DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000);
		super.printJSON(new JsonMsg(-1, "操作成功！", mchnt_txn_ssn));
		return null;
	}

	/**
	 * 用户投资列表接口 suker.zhou
	 * 
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/tender/list")
	public void userTenderList( @ModelAttribute UserTender info) throws Exception {
		Integer id = Constant.strToInt(info.getUid());
		/*if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}*/
		if(id != -1) {
			info.setUserId(id);
		}else{
			info.setLimit(99999);
		}
		super.printJSON(new JsonMsg(-1, "查询成功！", tenderService.listAll(info)));
		return;
	}

	/**
	 * 用户申请借款
	 * 
	 * @param vo
	 * @throws Exception
	 */
	@RequestMapping(value = "/borrow/apply")
	public void userBorrowApply( @ModelAttribute BorrowApply info) throws Exception {
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUserId(id);
		info.setStatus(1);
		info.setCreateTime(new Date());
		info.setTerminal("APP");
		borrowService.saveOrUpdateBorrowApply(info);
		super.printJSON(new JsonMsg(-1, "申请借款成功！"));
		return;
	}

	/**
	 * 提现列表
	 * 
	 * @param info
	 * @throws Exception
	 */
	@RequestMapping(value = "/withdraw/list")
	public void withdrawList( @ModelAttribute WithdrawRecordVo info) throws Exception {
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUserId(id);
		PageInfo<WithdrawRecordVo> allData=withdrawService.listWithdrawByStatus(info);
		super.printJSON(new JsonMsg(-1, "提现记录查询成功！", allData));
		return;
	}

	/**
	 * 充值列表查询
	 * @param info
	 * @throws Exception 
	 */
	@RequestMapping(value = "/recharge/list")
	public void rechargeList( @ModelAttribute RechargeRecord info) throws Exception {
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUserId(id);
		RechargeRecordVo rechargeRecordVo = new RechargeRecordVo();
		rechargeRecordVo.setUserId(id);
		CopyEntity.copy(info, rechargeRecordVo);
		super.printJSON(new JsonMsg(-1, "充值记录查询成功！", rechargeService.listByMethod(rechargeRecordVo)));
		return;
	}

	/**
	 * 新手标投资
	 * @param info	
	 * @param dealPassword	交易密码
	 * @throws Exception
	 */
	@RequestMapping(value = "/tender/new")
	public void addNewTender(@ModelAttribute UserTender info, 
			@RequestParam("dealPwd") String dealPwd,
			@RequestParam("amount") double amount) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		User user = userService.getById(id);
		if("N".equals(user.getIsnew())){
			super.printJSON(new JsonMsg(5, "新手标每个用户只能投资一次！"));
			return;			
		}
		if(user.getDealPassword()==null|| user.getDealPassword().equals("")){
			super.printJSON(new JsonMsg(2, "请设置交易密码！"));
			return;
		}
		if(dealPwd == null || dealPwd.equals("")){
			super.printJSON(new JsonMsg(3, "请填写交易密码！"));
			return;
		}
		if(!SHA.encryptPassword(dealPwd).equals(user.getDealPassword())){
			super.printJSON(new JsonMsg(4, "交易密码输入错误！"));
			return;
		}
		UserAccount account=userAccountService.getByUserId(user.getId());
		Borrow borrow = borrowService.detailBorrow(info.getBorrowId());
		if(amount<borrow.getMin()){
			super.printJSON(new JsonMsg(4, "投资金额最小为:"+borrow.getMin()+",请重新投资!"));
			return;			
		}
		if(amount>borrow.getMax()){
			super.printJSON(new JsonMsg(4, "投资金额最大为:"+borrow.getMax()+",请重新投资!"));
			return;			
		}		
		if(amount>borrow.getNotTenderMoney()){
			super.printJSON(new JsonMsg(7, "该新手标可投金额不足,请选择其它标进行投资!"));
			return;			
		}
		if(account.getBalance()<amount){
			super.printJSON(new JsonMsg(6, "账户可用余额不足,请先充值!"));
			return;
		}

		info.setUserId(id);
		info.setChanges("N");
		info.setRepayFinish("N");
		info.setAmount(amount);
		info.setCreateTime(new Date());
		info.setIsAuto("N");
		info.setCode(BaseUtil.generateCode(BaseUtil.TOUZI));
		Integer tenderId = tenderService.saveOrUpdateUserTender(info);
		if("Y".equals(user.getIsnew())){
			user.setIsnew("N");
			userService.saveOrUpdate(user);
		}
		super.printJSON(new JsonMsg(-1, "投资成功！"));
		return;
	}
	

	/**
	 * 用户投资
	 * @param info	
	 * @param dealPassword	交易密码
	 * @throws Exception
	 */
	@RequestMapping(value = "/tender/add")
	public void addTender(@ModelAttribute UserTender info) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		User user=new User();
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}else{
			user=userService.getById(id);
			if(user==null){
				super.printJSON(new JsonMsg(2, "非法登录"));
				return ;
			}else if("N".equals(user.getFuionAccount())){
				super.printJSON(new JsonMsg(3, "该账户还未开户，请先开户再继续操作"));
				return ;
			}
//			else{
//				if(!user.getDealPassword().equals(MD5.GetMD5Code(dealPassword))){
//					printJSON(new JsonMsg(2, "交易密码错误！"));
//					return;					
//				}
//			}
		}		
		Borrow borrow = borrowService.detailBorrow(info.getBorrowId());
		BorrowApply borrowApply = borrowService.getBorrowApply(borrow.getBorrowApplyId());
		
		if("expire".equals(borrow.getStatus())){
			super.printJSON(new JsonMsg(2, "该标为流标，不可投！"));
			return;			
		}
		if (borrowApply.getUserId().equals(user.getId())) {
			printJSON(new JsonMsg(4, "该借款标由您发起，您自己不能投标！"));
			return;
		}
		
		//查询金账户用户可用余额
		UserAccount accountFY = fuionAccountController.getFuionAccountBalance(user);
		if(accountFY.getBalance() < info.getAmount()){
			printJSON(new JsonMsg(4, "您的金账户可用余额为￥"+accountFY.getBalance()+"元，投标金额超过此金额，无法投标。"));
			return;
		}
		
		UserAccount account=userAccountService.getByUserId(user.getId());
		if(account.getBalance()<info.getAmount()){
			super.printJSON(new JsonMsg(3, "账户可用余额不足,请先充值!"));
			return;
		}		
		
		Double amount=info.getAmount();
		if(amount == null || borrow.getMin()==null || borrow.getMin()==0){
			if(amount%50 != 0){
				printJSON(new JsonMsg(4, "投标金额最低为"+borrow.getMin()+"元，请重新输入！"));
				return;
			}
		}else{
			if (amount<borrow.getMin() || amount%100 != 0) {
				printJSON(new JsonMsg(5, "投标金额最低为"+borrow.getMin()+"元，且最小投标金额必须是100.0的整数倍，请重新输入！"));
				return;
			}
		}  
		
		if (borrow.getNotTenderMoney() == null || borrow.getNotTenderMoney() <= 0d) {
			printJSON(new JsonMsg(6, "剩余可投金额不足，投标失败！"));
			return;
		}
		
		if(amount < borrow.getMin() || amount > borrow.getMax()){
			printJSON(new JsonMsg(7, "投资金额应大于等于"+borrow.getMin()+"小于等于"+borrow.getMax()));
			return;
		}
		if (amount > borrow.getNotTenderMoney()) {
			printJSON(new JsonMsg(8,"投资金额应该小于等于剩余可投金额！",borrow.getNotTenderMoney()));
			return;
		}
		Double money = tenderService.sumMoney(user.getId(), info.getBorrowId());
		if((money+amount) > borrow.getMax()){
			printJSON(new JsonMsg(9, "累计投资金额应小于"+borrow.getMax()));
			return;
		}
		UserAccount userAccount = userAccountService.getByUserId(user.getId());
		if(userAccount.getBalance() < amount ){
			printJSON(new JsonMsg(10, "用户可用金额不足，请充值！"));
			return;
		}
		printJSON(new JsonMsg(-1, "操作成功！"));
		
		return;
	}
	
	/**
	 * 我的投资
	 * @param info	必传status(状态),uid(用户id)
	 * @throws Exception
	 */
	@RequestMapping(value = "/tender/my")
	public void MyTender(@ModelAttribute UserTenderVo info) throws Exception{
		Integer id = Constant.strToInt(info.getUid());
		if (id == -1) {
			super.printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		info.setUserId(id);
		super.printJSON(new JsonMsg(-1, "我的投资查询成功！",tenderService.myTender(info)));
		return;
	}
	
	@RequestMapping("/fund/record")
	public String fundRecord(@RequestParam(value="uid") Integer uid,
							 @RequestParam(value="index",required=false,defaultValue="1") Integer index,
							 @RequestParam(value="terminal",required=false) String terminal) throws Exception{
		FundRecordUserVo record=new FundRecordUserVo();
		record.setUserId(uid);
		record.setIndex(index);
		PageInfo<FundRecordUserVo> pageInfo=fundRecordService.list(record);
		List<FundRecordTypeVo> typeList=FundRecordType.toList(FundRecordType.Type.values());
		for(FundRecordUserVo fundRecordUserVo : pageInfo.getPageList()){
			for(FundRecordTypeVo fundRecordTypeVo : typeList){
				if(fundRecordUserVo.getType() == fundRecordTypeVo.getIndex()){
					fundRecordUserVo.setTypeName(fundRecordTypeVo.getName());
				}
			}
		}
		super.printJSON(new JsonMsg(-1, "操作成功！",pageInfo));
		return null;
	}
	
	@RequestMapping("/user/bank/detail")
	public String userBank(@RequestParam(value="uid") Integer uid) throws Exception{
		BankCardVo vo = new BankCardVo();
		vo.setUserId(uid);
		List<BankCardVo> list = bankCardService.listDefaultCard(vo);
		if(list != null && list.size() > 0) {
			vo = list.get(0);
		}
		super.printJSON(new JsonMsg(-1, "操作成功！",vo));
		return null;
	}
	
	
}
